package cn.gaily.eduservice.service.impl;

import cn.gaily.eduservice.entity.EduChapter;
import cn.gaily.eduservice.entity.EduVideo;
import cn.gaily.eduservice.entity.vo.ChapterVo;
import cn.gaily.eduservice.entity.vo.VideoVo;
import cn.gaily.eduservice.mapper.EduChapterMapper;
import cn.gaily.eduservice.service.EduChapterService;
import cn.gaily.eduservice.service.EduVideoService;
import cn.gaily.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author xuchengwei
 * @since 2021-07-05
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Autowired
    private EduVideoService eduVideoService;

    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {
        //查EduChapter所有封装为list
        QueryWrapper<EduChapter> eduChapterQueryWrapper = new QueryWrapper<>();
        eduChapterQueryWrapper.eq("course_id",courseId);
        List<EduChapter> result = baseMapper.selectList(eduChapterQueryWrapper);
        //查EduVideo所有封装为list
        QueryWrapper<EduVideo> eduVideoQueryWrapper = new QueryWrapper<>();
        eduVideoQueryWrapper.eq("course_id",courseId);
        List<EduVideo> result2 = eduVideoService.list(eduVideoQueryWrapper);
        //封装为一个finalList
        ArrayList<ChapterVo> finalList = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(result.get(i),chapterVo);
            ArrayList<VideoVo> tmp = new ArrayList<>();
            for (int j = 0; j < result2.size(); j++) {
                if(result2.get(j).getChapterId().equals(chapterVo.getId())){
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(result2.get(j),videoVo);
                    tmp.add(videoVo);
                }
            }
            chapterVo.setChildren(tmp);
            finalList.add(chapterVo);
        }
        return finalList;
    }

    @Override
    public int deleteChapterById(String chapterId) {
        QueryWrapper<EduVideo> eduVideoQueryWrapper = new QueryWrapper<>();
        eduVideoQueryWrapper.eq("chapter_id",chapterId);
        int count = eduVideoService.count(eduVideoQueryWrapper);
        if(count == 0){
            int delete = baseMapper.deleteById(chapterId);
            return delete;
        }else {
            throw  new GuliException(20001,"还有小节，无法删除");
        }
    }
}
